package ipc

import (
	"encoding/json"
	"fmt"
)

type (
	Request struct {
		Method string
		Params string
	}
	Response struct {
		Code string
		Body string
	}
	Server interface {
		Name() string
		Handle(method, params string) *Response
	}
	IpcServer struct {
		Server
	}
)

func NewIpcServer(server Server) *IpcServer {

	return &IpcServer{server}

}

func (server *IpcServer) Connect() chan string {
	session := make(chan string, 0)

	go func(c chan string) {

		for {

			var Req Request

			request := <-c

			if request == "CLOSE" {
				break
			}

			err := json.Unmarshal([]byte(request), &Req)

			if err != nil {
				fmt.Println("Invalid request format : ", request)
			}

			resp := server.Handle(Req.Method, Req.Params)

			b, err := json.Marshal(resp)

			c <- string(b) //通知消息 字符

		}

		fmt.Println("Session Closed !")

	}(session)

	fmt.Println("A new IpcServer Session Created Successfully !")

	return session

}
